package com.llkj.youdaocar;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.llkj.youdaocar.httpUtils.AnsynHttpRequest;
import com.llkj.youdaocar.utils.SpUtil;
import com.llkj.youdaocar.utils.SystemBarTintManager;
import com.llkj.youdaocar.utils.Utils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import io.reactivex.FlowableEmitter;
import io.reactivex.internal.disposables.ListCompositeDisposable;
import rx.functions.Action1;


/**
 *
 */
public abstract class BaseActivity extends AppCompatActivity implements AnsynHttpRequest.ObserverCallBack{
	private ListCompositeDisposable listCompositeDisposable;
	protected String TAG = this.getClass().getSimpleName();
	protected Context mContext;
	protected ProgressDialog pd;
	private volatile static int act_in_foreground = 0;
	protected boolean mPermission = false;
	public SpUtil sputil;
	protected SystemBarTintManager systemBarTintManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		setContentView(getLayoutId());
		systemBarTintManager = Utils.setStatusBarFontColor(this, true);
		new RxPermissions(this)
				.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
				.subscribe(new Action1<Boolean>() {
					@Override
					public void call(Boolean aBoolean) {
						mPermission = aBoolean;
					}
				});

		sputil = SpUtil.init(getApplicationContext());

		ButterKnife.bind(this);
//		EventBus.getDefault().register(this);
		mContext = this;
		initView();
		initData();
		initListener();

		PushAgent.getInstance(this).onAppStart();
	}

	protected void initView() {

	}

	public static boolean isForeground() {
		return act_in_foreground > 0;
	}


	protected void initData() {
	}

	protected void initListener() {
	}

	protected abstract int getLayoutId();

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@CallSuper
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		act_in_foreground++;
//
	}

	@Override
	public void onStop() {
		super.onStop();
		act_in_foreground--;
		EventBus.getDefault().unregister(this);
		OkHttpUtils.getInstance().cancelTag(this);
	}
	@CallSuper
	@Override
	protected void onDestroy() {
		clear();
		mContext = null;
		super.onDestroy();
	}

	public ListCompositeDisposable getComp() {
		if (this.listCompositeDisposable == null) {
			this.listCompositeDisposable = new ListCompositeDisposable();
		}
		return listCompositeDisposable;
	}

	protected void clear() {
		if (!getComp().isDisposed()) {
			getComp().clear();
		}
	}

	@Override
	public Resources getResources() {
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());
		return res;
	}

	/**
	 * [页面跳转]
	 *
	 * @param clz
	 */
	public void startActivity(Class<?> clz, @Nullable Intent data) {
		Intent intent;
		if (data != null) {
			intent = new Intent(data);
		} else {
			intent = new Intent();
		}
		intent.setClass(mContext, clz);
		startActivity(intent);
	}

	/**
	 * 全局等待对话框
	 */
	public void showWaitDialog() {
		//如果ctx等于空或者isFinishing
		if (mContext == null || isFinishing())
			return;
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (pd == null
						|| !pd.isShowing()) {
					pd = new ProgressDialog(mContext);
					pd.setMessage("加载中...");
					pd.setCancelable(true);
					pd.show();
				}

			}
		});

	}

	public void dismissWaitDialog() {
		if (mContext == null || isFinishing())
			return;
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (pd != null
						&& pd.isShowing()) {
					pd.dismiss();
					pd = null;
				}
			}
		});

	}

	@Override
	public void handleResult(String data, int encoding, int method) {
		dismissWaitDialog();
		switch (encoding) {
			case AnsynHttpRequest.SUCCESS_HTTP:
				try {
					JSONObject jsonObject = new JSONObject(data);
					if (jsonObject.has("code") && jsonObject.getInt("code") == 0) {
						onhttpSuccess(data, method);
					}else {
						onhttpFailed(jsonObject.getString("message"), method);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					onhttpFailed("数据请求失败", method);
				}
				break;
			case AnsynHttpRequest.FAILURE_HTTP:
				onhttpFailed("数据请求失败", method);
				break;
			case AnsynHttpRequest.FAILURE_NETWORK:
				onhttpFailed(null, method);
				break;
		}
	}
	protected void onhttpSuccess(String data, int method) {
		dismissWaitDialog();
	}

	protected void onhttpFailed(String message, int method) {
		dismissWaitDialog();
//        if (!StringUtils.isEmpty(message)) {
//            ToastUtil.makeShortText(this, message);
//        }
	}
}
